package com.gxa.ehome.web.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.ehome.exception.BusinessException;
import com.gxa.ehome.util.JsonResult;
import com.gxa.ehome.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

// 集中异常的处理方式
//@WebServlet(name = "ExceptionHandlerServlet", urlPatterns = "/exception.do")
public class ExceptionHandlerServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        Exception e = (Exception) request.getAttribute("e");
        Exception e = new Exception("nihao");//用来测试的异常
        System.out.println(e);
        if (e instanceof BusinessException) {
            JsonResult result = new JsonResult();
            result.setCode("0");
            result.setMsg(((Exception) e).getMessage());

            String s = JSON.toJSONString(request);

            // 发送给前端 使用的是一个封装方法
            ResponseUtil.send(response, s);
        } else {
            //记录日志
            //目标:把异常信息记录到error.log文件中
            //java中获取当前时间并且格式化
            //这里是通过动态的生成文件然后再写入文件,用时间拼接成文件名 error2021-05-07.log
//
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
//            System.out.println(format);
            String filedate = format.substring(0, 10);
//            System.out.println(filedate);
            String fileName="error"+filedate+".log";
//            System.out.println(fileName);//文件名测试
            String realPath1 = this.getServletContext().getRealPath("/log");
            System.out.println(realPath1);
            //先生成log文件夹
            String filepa=realPath1;
            File file1=new File(filepa);
            if (!file1.exists()){
                file1.mkdir();
                System.out.println("进入了生成文件夹");
            }
            //文件的最终路径
            //生成的log文件夹下的文件
            String filepath=realPath1+ File.separator+fileName;
            System.out.println(filepath);//路径测试
            File file = new File(filepath);
            if (!file.exists()){
                file.createNewFile();
                System.out.println("进入了生成日志文件");
            }
//
//
//            String realPath = this.getServletContext().getRealPath(filepath);
            //写日志进刚刚建的文件
            FileWriter writer = new FileWriter(file, true);
//            FileWriter writer = new FileWriter(realPath, true);

            StringBuilder builder = new StringBuilder();

            //异常类型
            String s = e.toString();
            //异常消息
            String message = e.getMessage();//消息

            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                String s1 = stackTraceElement.toString();
                //把这个内容写到流当中追加
                builder.append(s1);
            }
            //完成字符串追加后,向流中写
            writer.write(builder.toString());
            writer.flush();
            writer.close();


            //--------------------------
            //时间
            //异常类型
            //异常的原因
            //发生的轨迹

        }


    }

    // 接收前端的get类型的请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 调用doGet方法, 合二为一
        doPost(request, response);
//        System.out.println("异常对象被传递了");
//        Enumeration<String> attributeNames = request.getAttributeNames();
////        while (attributeNames.hasMoreElements()){
////            String s = attributeNames.nextElement();
////            System.out.println(s);
////
////        }
////        javax.servlet.forward.request_uri
////        javax.servlet.forward.context_path
////        javax.servlet.forward.servlet_path
////        javax.servlet.forward.mapping
////        javax.servlet.error.status_code
////        javax.servlet.error.exception_type
////        javax.servlet.error.message
////        javax.servlet.error.servlet_name
////        javax.servlet.error.request_uri
////        javax.servlet.error.exception
//
//        Object attribute = request.getAttribute("javax.servlet.error.exception");
//        System.out.println(attribute);
//        Object attribute1 = request.getAttribute("javax.servlet.error.status_code");
//        System.out.println(attribute1);
//        Object attribute2 = request.getAttribute("javax.servlet.error.exception_type");
//        System.out.println(attribute2);
//        Object attribute3 = request.getAttribute("javax.servlet.error.message");
//        System.out.println(attribute3);
//        Object attribute4 = request.getAttribute("javax.servlet.error.request_uri");
//        System.out.println(attribute4);
//        Object attribute5 = request.getAttribute("javax.servlet.error.servlet_name");
//        System.out.println(attribute5);


    }
}
